// Package imports:
import 'package:date_format/date_format.dart';
import 'package:palmf_hid/common/apis/api.dart';
import 'package:palmf_hid/common/entities/data_base/my_database.dart';
import 'package:palmf_hid/common/entities/event/result_refresh_event.dart';
import 'package:palmf_hid/common/services/Db.dart';
import 'package:palmf_hid/common/utils/utils.dart';
import 'package:palmf_hid/pages/main/check/check_logic.dart';

// Project imports:

//数据回传保存到数据库，
/// isHasCurveVersion 是否有曲线版本号信息
Future<void> dataFeedback(
  String mac,
  String projectName,
  String resultUnit,
  double resultD,
  String curveBatchNo,
  int sample,
  String resultDisplay,
  String deviceNo,
  int saveNum,
  int patientId,
  String position,
  String scanCode,
  String lower,
  String upper,
  String referLower,
  String referUpper,
  int curveVersion, {
  DateTime? palmfTime,
  int? jointInspectionNo,
  int? jointInspectionNum,
}) async {
  DateTime currentTime = DateTime.now();
  //按照条件查重，如果没有添加到数据库，并上传服务器
  List<Results> value = await DbService.to.queryResultTheSame(mac, resultD,
      saveNum, resultDisplay, projectName, patientId, currentTime);
  String lotNum = MyRegUtil.isNumAndLetter(curveBatchNo.toString().trim())
      ? curveBatchNo.toString().trim()
      : "";
  if (jointInspectionNo != null && jointInspectionNum != null) {
    MyLogUtil().i("返回测试结果");
  }
  if (value.isEmpty) {
    ///数据库没有做版本升级，没有增加服务器保存的曲线版本字段，把版本号信息拼接在了 identityCode后面用@分割
    DbService.to
        .addResult(ResultEntityCompanion.insert(
            mac: mac,
            projectName:
                projectName.replaceAll('\u0000', "").replaceAll(" ", ""),
            resultUnit: resultUnit,
            result: resultD,
            curveBatchNo: lotNum,
            sample: sample,
            resultDisplay: resultDisplay,
            deviceNo: deviceNo,
            identityCode: curveVersion.toString(),
            //曲线版本号
            time: palmfTime ?? DateTime.now(),
            lastSyncTime: DateTime.now(),
            patientId: patientId,
            position: position,
            saveNum: saveNum ?? 0,
            lower: lower,
            upper: upper,
            referLower:
                projectName.replaceAll('\u0000', "").replaceAll(" ", "") ==
                        "PGI/PGII"
                    ? '3'
                    : referLower,
            referUpper: referUpper,
            upload: false,
            jointInspectionNo: jointInspectionNo.toString(),
            jointInspectionNum: jointInspectionNum.toString(),
            otherOne: '',
            otherTwo: '',
            otherThree: ''))
        .then((resultId) {
      MyLogUtil().i("插入数据的自增ID：$resultId");
      Map<String, dynamic> params = {};
      params["projectName"] =
          projectName.replaceAll('\u0000', "").replaceAll(" ", "");
      params["sample"] = sample == -1 ? "" : sample;
      params["resultUnit"] =
          resultUnit.replaceAll('\u0000', "").replaceAll(" ", "");
      params["resultDisplay"] = resultDisplay;
      params["result"] = resultD.toString();
      params["deviceNo"] = deviceNo;
      params["time"] = formatDate(
          DateTime.now(), [yyyy, '-', mm, '-', dd, " ", HH, ':', nn, ':', ss]);
      params["identityCode"] = scanCode;
      params["curveBatchNo"] = lotNum;
      params["curveVersion"] = curveVersion.toString();
      params["patientId"] = patientId;
      params["position"] = position;
      params["scale"] = saveNum;
      params["mac"] = mac;
      MyLogUtil().i('上传服务器参数：$params');
      ApiRepository.dataBackup(params).then((value) {
        if (value.code == 0) {
          DbService.to.updateResultUpload(resultId);
        }
      });
    }, onError: (e) {
      MyLogUtil().i("$e");
    });
  } else {
    MyLogUtil().i("走这里了吗");
  }
  ResultRefreshEvent loginEvent = ResultRefreshEvent();
  loginEvent.isRefresh = true;
  resultRefreshEventInEventBus.fire(loginEvent);
}
